package com.nmdl.print;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.UriUtils;
import com.hprt.lib.mt800.DensityLevel;
import com.hprt.lib.mt800.HPRTPrinterHelper;
import com.hprt.lib.mt800.PrinterState;
import com.hprt.lib.mt800.PrinterStatus;
import com.hprt.lib.mt800.exception.CustomerCodeException;
import com.hprt.lib.mt800.listener.PrinterStateListener;
import com.nmdl.print.utils.BlueUtils;
import com.nmdl.print.utils.DeviceConnectFragment;
import com.nmdl.print.utils.Download;
import com.nmdl.print.utils.PrintFragment;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final int SELECT_PDF = 1200;
    BluetoothDevice bluetoothDevice;
    boolean connectRes = false;
    ViewHolder viewHolder;
    File pdfFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewHolder = new ViewHolder();
    }

    /**
     * 连接设备
     */
    public void connectDevice(View view) {
        DeviceConnectFragment deviceConnectFragment = DeviceConnectFragment.newInstance(device -> {
            bluetoothDevice = device;
            viewHolder.blue_name_tv.setText("蓝牙名称：" + device.getName());
            try {
                connectRes = HPRTPrinterHelper.INSTANCE.connect(bluetoothDevice.getAddress());
                showShort(connectRes ? "连接成功！" : "连接失败！");
            } catch (CustomerCodeException e) {
                showShort(R.string.customer_code_error);
            }
            runOnUiThread(() -> {
                try {
                    viewHolder.showStartPrint();
                    getDeviceInfo();
                    Thread.sleep(1000);
                    viewHolder.bondStateListener();
                    getDeviceState(null);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        });
        FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
        deviceConnectFragment.show(fragmentManager, "DeviceConnectFragment");
    }

    /**
     * 下载pdf文件
     */
    @SuppressLint("WrongConstant")
    public void downPdf(View view) {
        boolean granted = PermissionUtils.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!granted) {
            PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callback(new PermissionUtils.SimpleCallback() {
                        @Override
                        public void onGranted() {
                            downPdf(null);
                        }

                        @Override
                        public void onDenied() {
                            showShort("权限申请失败！");
                        }
                    })
                    .request();
            return;
        }
        viewHolder.download_btn.setEnabled(false);
        viewHolder.download_pb_layout.setVisibility(View.VISIBLE);
        String downloadUrl = "https://www.gjtool.cn/pdfh5/git.pdf";
//        String downloadUrl = "https://cdn2.jianshu.io/assets/default_avatar/5-33d2da32c552b8be9a0548c7a4576607.jpg";
        Download.downLoadFile(downloadUrl, new Download.OnDownBack() {
            @Override
            public void onSuccess(String path) {
                runOnUiThread(() -> {
                    showShort("下载完成！");
                    viewHolder.download_btn.setEnabled(true);
                });
            }

            @Override
            public void onProgress(int progress) {
                viewHolder.download_pb.setProgress(progress);
            }

            @Override
            public void onFail() {
                runOnUiThread(() -> {
                    showShort("下载失败！");
                    viewHolder.download_btn.setEnabled(true);
                });
            }
        });
    }

    /**
     * 选择pdf文件
     */
    public void selectPdf(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/pdf");
        startActivityForResult(intent, SELECT_PDF);
    }

    /**
     * 开始打印
     */
    public void startPrint(View view) {
        if (!connectRes) {
            showShort("请先连接打印机！");
            return;
        }
        getDeviceState(msg -> {
            runOnUiThread(() -> {
                if (!msg.equals("打印机就绪")) {
                    showShort(msg);
                    return;
                }
                if (pdfFile != null) {
                    Bitmap printBitmap = HPRTPrinterHelper.INSTANCE.pdfToPrintImage(pdfFile, 0);
                    //type ->0:二值, 1：文档, 2:图片, 无参数做二值处理
                    HPRTPrinterHelper.INSTANCE.preparePrint();
                    Boolean result = HPRTPrinterHelper.INSTANCE.printBitmap(printBitmap, 1);
                    showShort("打印结果:" + result);
                } else {
                    showShort("请选择PDF文件!");
                }
            });
        });
    }

    /**
     * 打印一体化
     */
    public void printProcess(View view) {
        String pdfUrl = "https://www.gjtool.cn/pdfh5/git.pdf";
        PrintFragment printFragment = PrintFragment.newInstance(pdfUrl);
        FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
        printFragment.show(fragmentManager, "PrintFragment");
    }

    private void getDeviceInfo() {
        HPRTPrinterHelper.INSTANCE.getPrintName(s -> viewHolder.device_name_tv.setText("设备名称：" + s));
        HPRTPrinterHelper.INSTANCE.getPrinterNo(s -> viewHolder.device_number_tv.setText("设备编号：" + s));
        HPRTPrinterHelper.INSTANCE.getFirmwareVersion(s -> viewHolder.device_firmware_code_tv.setText("固件版本：" + s));
        HPRTPrinterHelper.INSTANCE.getCarbonNo(s -> viewHolder.device_carbon_belt_tv.setText("碳带型号：" + s));
        HPRTPrinterHelper.INSTANCE.getCarbonSurplus(i -> viewHolder.device_carbon_belt_remain_tv.setText("碳带剩余：" + i + " (单位:mm)"));
    }

    private void getDeviceState(GetStateListener getStateListener) {
        HPRTPrinterHelper.INSTANCE.checkState();
        this.getStateListener = getStateListener;
    }

    private void initStateListener() {
        HPRTPrinterHelper.INSTANCE.attachPrinterStateListener(new PrinterStateListener() {
            @Override
            public void onState(int state) {
                if (getStateListener != null) {
                    getStateListener.backState(getState(state));
                    getStateListener = null;
                }
            }

            @Override
            public void onBattery(int i) {

            }

            @Override
            public void onStandbyTime(int i) {

            }

            @Override
            public void onDensity(int i) {

            }

            @Override
            public void onMode(int i) {

            }

            @Override
            public void onTemperature(int i) {

            }

            @Override
            public void onPrinterStatus(PrinterStatus printerStatus) {
                runOnUiThread(() -> {
                    viewHolder.device_electric_tv.setText("电量状态：" + printerStatus.getBattery() + "%");
                    String standByTime = printerStatus.getTime() != 0 ? printerStatus.getTime() + "Min" : "永不关机";
                    viewHolder.device_can_time_tv.setText("待机时间：" + standByTime);
                    viewHolder.device_print_density_tv.setText("打印浓度：" + getDensity(printerStatus.getDensity()));
                    viewHolder.device_print_model_tv.setText("打印模式：" + (printerStatus.getMode() == 0 ? "热敏纸" : "A4纸"));
                    viewHolder.device_temperature_tv.setText("设备温度：" + (printerStatus.getTemperature() + "℃"));
                    viewHolder.device_free_tv.setText("是否空闲：" + (printerStatus.isIdle() ? "是" : "否"));
                    viewHolder.device_cache_state_tv.setText("缓冲区状态：" + (printerStatus.isBuffIsNull() ? "空" : "非空"));
                    viewHolder.device_state_tv.setText("设备状态：" + getState(printerStatus.getState()));
                });
            }
        });
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            showShort("选择成功！");
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            pdfFile = BlueUtils.uriToFileApiQ(result, this);
            viewHolder.showStartPrint();
            viewHolder.file_path_tv.setText("文件路径：" + pdfFile.getPath());
//            viewHolder.pdf_num_tv.setText("PDF页码：" + PdfiumCore.);
        } else if (resultCode == RESULT_CANCELED) {
            showShort("取消选择！");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HPRTPrinterHelper.INSTANCE.disconnect();
    }

    GetStateListener getStateListener;

    interface GetStateListener {
        void backState(String msg);
    }

    class ViewHolder {
        TextView blue_name_tv;
        TextView device_name_tv;
        TextView device_number_tv;
        TextView device_firmware_code_tv;
        TextView device_carbon_belt_tv;
        TextView device_carbon_belt_remain_tv;
        Button bond_btn;
        Button un_bond_btn;
        Button check_state_btn;
        Button start_print_btn;
        Button download_btn;
        FrameLayout download_pb_layout;
        ProgressBar download_pb;
        TextView device_state_tv;
        TextView device_electric_tv;
        TextView device_can_time_tv;
        TextView device_print_density_tv;
        TextView device_print_model_tv;
        TextView device_temperature_tv;
        TextView device_free_tv;
        TextView device_cache_state_tv;
        TextView file_path_tv;
        TextView pdf_num_tv;

        public ViewHolder() {
            blue_name_tv = findViewById(R.id.blue_name_tv);
            //设备信息
            device_name_tv = findViewById(R.id.device_name_tv);
            device_number_tv = findViewById(R.id.device_number_tv);
            device_firmware_code_tv = findViewById(R.id.device_firmware_code_tv);
            device_carbon_belt_tv = findViewById(R.id.device_carbon_belt_tv);
            device_carbon_belt_remain_tv = findViewById(R.id.device_carbon_belt_remain_tv);
            //设备状态
            bond_btn = findViewById(R.id.bond_btn);
            un_bond_btn = findViewById(R.id.un_bond_btn);
            check_state_btn = findViewById(R.id.check_state_btn);
            start_print_btn = findViewById(R.id.start_print_btn);
            download_btn = findViewById(R.id.download_btn);
            download_pb_layout = findViewById(R.id.download_pb_layout);
            download_pb = findViewById(R.id.download_pb);
            device_state_tv = findViewById(R.id.device_state_tv);
            device_electric_tv = findViewById(R.id.device_electric_tv);
            device_can_time_tv = findViewById(R.id.device_can_time_tv);
            device_print_density_tv = findViewById(R.id.device_print_density_tv);
            device_print_model_tv = findViewById(R.id.device_print_model_tv);
            device_temperature_tv = findViewById(R.id.device_temperature_tv);
            device_free_tv = findViewById(R.id.device_free_tv);
            device_cache_state_tv = findViewById(R.id.device_cache_state_tv);
            file_path_tv = findViewById(R.id.file_path_tv);
            pdf_num_tv = findViewById(R.id.pdf_num_tv);
            setListener();
        }

        private void setListener() {
            check_state_btn.setOnClickListener(view -> getDeviceState(null));
            bond_btn.setOnClickListener(view -> bondStateListener());
            un_bond_btn.setOnClickListener(view -> unBondStateListener());
        }

        private void bondStateListener() {
            initStateListener();
            bond_btn.setEnabled(false);
            un_bond_btn.setEnabled(true);
            check_state_btn.setEnabled(true);
        }

        private void unBondStateListener() {
            HPRTPrinterHelper.INSTANCE.detachPrinterStateListener();
            bond_btn.setEnabled(true);
            un_bond_btn.setEnabled(false);
            check_state_btn.setEnabled(false);
        }

        private void showStartPrint() {
            if (pdfFile != null && connectRes) start_print_btn.setEnabled(true);
        }
    }

    private String getResString(int resId) {
        return getResources().getText(resId).toString();
    }

    private void showShort(int resId) {
        showShort(getResources().getText(resId).toString());
    }

    private void showShort(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private String getDensity(int density) {
        String densityStr = "";
        switch (density) {
            case DensityLevel.LOW:
                densityStr = "低";
                break;
            case DensityLevel.MID:
                densityStr = "中";
                break;
            case DensityLevel.HIGH:
                densityStr = "高";
                break;
        }
        return densityStr;
    }

    private String getState(int state) {
        String stateStr = "";
        switch (state) {
            case PrinterState.TEMP_TOO_HIGH:
                stateStr = "打印机温度过高!";
                break;
            case PrinterState.POWER_LOW:
                stateStr = "打印机电量过低!";
                break;
            case PrinterState.UNCAP:
                stateStr = "打印机开盖!";
                break;
            case PrinterState.CARBON_MISS:
                stateStr = "打印机碳带用尽!";
                break;
            case PrinterState.PAPER_MISS:
                stateStr = "打印机缺纸!";
                break;
            case PrinterState.PAPER_ERROR:
                stateStr = "打印机纸装歪了!";
                break;
            case PrinterState.AUTH_MILEAGE_END:
            case PrinterState.NO_OFFICIAL_CARBON:
                stateStr = "打印机碳带未匹配!";
                break;
            case PrinterState.NORMAL:
                stateStr = "打印机就绪";
                break;
            default:
                stateStr = "打印机状态异常!";
                break;
        }
        return stateStr;
    }
}
